package com.example.tnot.Util.popupwindow;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.example.tnot.R;

import java.util.Calendar;

public class WheelDateTimePickerPopup {

    private Context context;
    private PopupWindow popupWindow;
    private NumberPicker yearPicker, monthPicker, dayPicker, hourPicker, minutePicker;
    private OnDateTimeSelectedListener listener;
    private View anchorView;
    private TextView tv_confirm;

    private int currentYear, currentMonth, currentDay;

    public WheelDateTimePickerPopup(Context context, View anchorView) {
        this.context = context;
        this.anchorView = anchorView;

        Calendar calendar = Calendar.getInstance();
        currentYear = calendar.get(Calendar.YEAR);
        currentMonth = calendar.get(Calendar.MONTH) + 1;
        currentDay = calendar.get(Calendar.DAY_OF_MONTH);

        initPopupWindow();
    }

    private void initPopupWindow() {
        // 使用 Application Context 避免内存泄漏
        Context appContext = context.getApplicationContext();
        LayoutInflater inflater = LayoutInflater.from(appContext);
        View contentView = inflater.inflate(R.layout.popup_wheel_picker, null);

        popupWindow = new PopupWindow(
                contentView,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                true // focusable
        );

        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(context.getResources().getDrawable(android.R.drawable.dialog_holo_light_frame));
//
//        // 设置动画
//        popupWindow.setAnimationStyle(R.style.PopupAnimation);

        initViews(contentView);
        setupPickers();
        setListeners();
        customizeNumberPickers();
    }

    private void initViews(View contentView) {
        tv_confirm = contentView.findViewById(R.id.tv_confirm);
        yearPicker = contentView.findViewById(R.id.yearPicker);
        monthPicker = contentView.findViewById(R.id.monthPicker);
        dayPicker = contentView.findViewById(R.id.dayPicker);
        hourPicker = contentView.findViewById(R.id.hourPicker);
        minutePicker = contentView.findViewById(R.id.minutePicker);
    }

    private void setupPickers() {
        // 设置年份 (2023-2027)
        yearPicker.setMinValue(2023);
        yearPicker.setMaxValue(2027);
        yearPicker.setValue(currentYear);
        yearPicker.setWrapSelectorWheel(false);

        // 设置月份
        monthPicker.setMinValue(1);
        monthPicker.setMaxValue(12);
        monthPicker.setValue(currentMonth);
        monthPicker.setWrapSelectorWheel(false);
        monthPicker.setFormatter(value -> String.format("%02d", value));

        // 设置日期
        updateDayPicker();

        // 设置小时
        hourPicker.setMinValue(0);
        hourPicker.setMaxValue(23);
        hourPicker.setValue(12);
        hourPicker.setWrapSelectorWheel(false);
        hourPicker.setFormatter(value -> String.format("%02d", value));

        // 设置分钟
        minutePicker.setMinValue(0);
        minutePicker.setMaxValue(59);
        minutePicker.setValue(0);
        minutePicker.setWrapSelectorWheel(false);
        minutePicker.setFormatter(value -> String.format("%02d", value));

        // 月份和年份变化时更新日期
        monthPicker.setOnValueChangedListener((picker, oldVal, newVal) -> updateDayPicker());
        yearPicker.setOnValueChangedListener((picker, oldVal, newVal) -> updateDayPicker());
    }

    private void updateDayPicker() {
        int year = yearPicker.getValue();
        int month = monthPicker.getValue();
        int maxDays = getDaysInMonth(year, month);

        int currentDayValue = dayPicker.getValue();
        dayPicker.setMinValue(1);
        dayPicker.setMaxValue(maxDays);
        dayPicker.setWrapSelectorWheel(false);
        dayPicker.setFormatter(value -> String.format("%02d", value));

        if (currentDayValue > maxDays) {
            dayPicker.setValue(maxDays);
        } else {
            dayPicker.setValue(Math.min(currentDayValue, maxDays));
        }
    }

    private int getDaysInMonth(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, 1);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    private void setListeners() {
        tv_confirm.setOnClickListener(v -> {
            if (listener != null) {
                Calendar selectedDateTime = Calendar.getInstance();
                selectedDateTime.set(
                        yearPicker.getValue(),
                        monthPicker.getValue() - 1,
                        dayPicker.getValue(),
                        hourPicker.getValue(),
                        minutePicker.getValue()
                );
                listener.onDateTimeSelected(selectedDateTime);
            }
            dismiss();
        });

        // 点击外部关闭
        popupWindow.setOnDismissListener(() -> {
            // 可以在这里处理关闭后的逻辑
        });
    }

    private void customizeNumberPickers() {
        // 自定义所有 NumberPicker 的外观
        customizeNumberPicker(yearPicker);
        customizeNumberPicker(monthPicker);
        customizeNumberPicker(dayPicker);
        customizeNumberPicker(hourPicker);
        customizeNumberPicker(minutePicker);
    }

    private void customizeNumberPicker(NumberPicker picker) {
        try {
            // 设置分割线颜色
            @SuppressLint("SoonBlockedPrivateApi") java.lang.reflect.Field selectionDivider = NumberPicker.class.getDeclaredField("mSelectionDivider");
            selectionDivider.setAccessible(true);
            selectionDivider.set(picker, context.getResources().getDrawable(R.drawable.picker_divider));
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            // 设置选中文本颜色和大小
            @SuppressLint("SoonBlockedPrivateApi") java.lang.reflect.Field selectorWheelPaintField = NumberPicker.class.getDeclaredField("mSelectorWheelPaint");
            selectorWheelPaintField.setAccessible(true);
            android.graphics.Paint wheelPaint = (android.graphics.Paint) selectorWheelPaintField.get(picker);
            wheelPaint.setColor(context.getResources().getColor(android.R.color.black));
            wheelPaint.setTextSize(18 * context.getResources().getDisplayMetrics().density);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void show() {
        if (popupWindow != null && !popupWindow.isShowing()) {
            // 检查 Activity 是否还存在
            if (context instanceof Activity) {
                Activity activity = (Activity) context;
                if (!activity.isFinishing() && !activity.isDestroyed()) {
                    // 在锚点视图下方显示
                    popupWindow.showAsDropDown(anchorView);

                    popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    popupWindow.setOutsideTouchable(true);

                    // 或者在屏幕底部显示（可选）
                    // popupWindow.showAtLocation(anchorView, Gravity.BOTTOM, 0, 0);
                }
            }
        }
    }

    public void dismiss() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }

    public void setSelectedDateTime(Calendar dateTime) {
        if (dateTime != null && popupWindow != null) {
            yearPicker.setValue(dateTime.get(Calendar.YEAR));
            monthPicker.setValue(dateTime.get(Calendar.MONTH) + 1);
            dayPicker.setValue(dateTime.get(Calendar.DAY_OF_MONTH));
            hourPicker.setValue(dateTime.get(Calendar.HOUR_OF_DAY));
            minutePicker.setValue(dateTime.get(Calendar.MINUTE));
        }
    }

    public void setOnDateTimeSelectedListener(OnDateTimeSelectedListener listener) {
        this.listener = listener;
    }

    public interface OnDateTimeSelectedListener {
        void onDateTimeSelected(Calendar selectedDateTime);
    }

    public boolean isShowing() {
        return popupWindow != null && popupWindow.isShowing();
    }
}